import json
import logging
import traceback
import pandas as pd
from datetime import datetime

from django.db import transaction
from django.views import View
from django.http import JsonResponse, HttpResponse
from rest_framework.status import HTTP_200_OK, HTTP_400_BAD_REQUEST
from Model.models import Equipment, Contract, IncomeDetail
from tools.Tools import getCurrentUser, createHandleLog, getFileBytes
from mgtServer.settings import MEDIA_ROOT

res = dict()
logger_info = logging.getLogger('info')


def downloadExample(request):
    res.clear()
    try:
        out_stream = getFileBytes('设备码上传文件说明及样例.xls')
        response = HttpResponse(content_type='application/vnd.ms-excel', charset="UTF-8")
        response.write(out_stream)
        return response
    except Exception as e:
        logger_info.error(f'当前接口：{request.path} 异常，异常内容为:{traceback.format_exc()}')
        res['status'] = 400
        res['messages'] = '请求错误'
        return JsonResponse(res, status=HTTP_400_BAD_REQUEST)


class EquipmentView(View):
    res.clear()

    def get(self, request, *args, **kwargs):
        try:
            current = request.GET.get("current")
            pageSize = request.GET.get("pageSize")
            equipment_type = request.GET.get("equipment_type")
            equipment_code = request.GET.get("equipment_code")
            dataInfo = Equipment.objects.all()
            if equipment_type is not None and equipment_type != '':
                dataInfo = dataInfo.filter(equipment_type=equipment_type)
            if equipment_code is not None and equipment_code != '':
                dataInfo = dataInfo.filter(equipment_code__contains=equipment_code)
            total = dataInfo.__len__()
            data = list(dataInfo.values()[int(pageSize) * int(current) - int(pageSize):int(pageSize) * int(current)])
            res['status'] = 200
            res['data'] = data
            res['total'] = total
            res['current'] = current
            res['pageSize'] = pageSize
            res['messages'] = '请求成功'
            return JsonResponse(res, status=HTTP_200_OK)
        except:
            logger_info.error(f'当前接口：{request.path} 异常，异常内容为:{traceback.format_exc()}')
            res['status'] = 400
            res['messages'] = '请求错误'
            return JsonResponse(res, status=HTTP_400_BAD_REQUEST)

    @transaction.atomic
    def post(self, request, *args, **kwargs):
        try:
            body = json.loads(request.body)
            upload_data = body.get('list')
            for data in upload_data:
                equipment_type, equipment_code = data.values()
                if equipment_code != "":
                    if not Equipment.objects.filter(equipment_code=equipment_code.strip()).exists():
                        createDate = Equipment.objects.create()
                        createDate.equipment_id = createDate.id
                        createDate.equipment_type = equipment_type.strip()
                        createDate.equipment_code = equipment_code.strip()
                        createDate.equipment_status = 1
                        createDate.use_status = 0
                        createDate.import_date = datetime.now()
                        createDate.save()
            res['status'] = 200
            res['message'] = '文件上传成功'
            return JsonResponse(res, status=HTTP_200_OK)
        except:
            logger_info.error(f'当前接口：{request.path} 异常，异常内容为:{traceback.format_exc()}')
            res['status'] = 400
            res['messages'] = '请求错误'
            return JsonResponse(res, status=HTTP_400_BAD_REQUEST)

    def delete(self, request, *args, **kwargs):
        try:
            code = request.GET.get('code')
            data = Equipment.objects.get(equipment_code=code)
            if data.use_status != 0:
                res['status'] = 400
                res['message'] = "该设备已被使用,删除失败"
            else:
                data.delete()
                createHandleLog('删除设备', str(getCurrentUser(request)), data.equipment_code)
                logger_info.info(
                    f'{getCurrentUser(request)} 在 {str(datetime.now())[:19]} 操作《删除设备》权限  操作内容 {data.equipment_code}')
                res['status'] = 200
                res['message'] = '删除成功'
            return JsonResponse(res, status=HTTP_200_OK)
        except:
            logger_info.error(f'当前接口：{request.path} 异常，异常内容为:{traceback.format_exc()}')
            res['status'] = 400
            res['messages'] = '请求错误'
            return JsonResponse(res, status=HTTP_400_BAD_REQUEST)


def SelectEqType(request):
    res.clear()
    try:
        if request.method == 'GET':
            dataInfo = list(Equipment.objects.all().values('equipment_type').distinct())
            res['data'] = dataInfo
            res['status'] = 200
            res['message'] = '请求成功'
            return JsonResponse(res, status=HTTP_200_OK)
    except:
        logger_info.error(f'当前接口：{request.path} 异常，异常内容为:{traceback.format_exc()}')
        res['status'] = 400
        res['messages'] = '请求错误'
        return JsonResponse(res, status=HTTP_400_BAD_REQUEST)


def getCodeByEqType(request):
    res.clear()
    try:
        if request.method == 'GET':
            equipment_type = request.GET.get('equipment_type')
            dataInfo = list(
                Equipment.objects.filter(equipment_type=equipment_type, use_status=0).values('equipment_code'))
            res['data'] = dataInfo
            res['status'] = 200
            res['message'] = '请求成功'
            return JsonResponse(res, status=HTTP_200_OK)
    except:
        logger_info.error(f'当前接口：{request.path} 异常，异常内容为:{traceback.format_exc()}')
        res['status'] = 400
        res['messages'] = '请求错误'
        return JsonResponse(res, status=HTTP_400_BAD_REQUEST)


@transaction.atomic
def modifyCode(request):
    """
    修改用户端设备
    """
    res.clear()
    try:
        if request.method == 'POST':
            body = json.loads(request.body)
            equipment_code = body.get('equipment_code')
            code = body.get('code')
            contractId = body.get('contractId')
            detailId = body.get('detailId')
            equipmentType = body.get('equipmentType')
            oldCodeData = Equipment.objects.get(equipment_code=equipment_code)
            newCodeData = Equipment.objects.get(equipment_code=code)
            contractData = Contract.objects.get(contract_id=contractId)
            detailData = IncomeDetail.objects.get(detail_id=detailId, equipment_type=equipmentType)
            oldCodeData.use_status = 0
            oldCodeData.access_number = None
            oldCodeData.start_date = None
            newCodeData.use_status = 2
            newCodeData.access_number = contractData.account_number
            newCodeData.start_date = datetime.now()
            detailData.equipment_code = code
            oldCodeData.save()
            newCodeData.save()
            detailData.save()
            res['status'] = 200
            res['message'] = '修改成功'
            createHandleLog('修改用户设备', str(getCurrentUser(request)), body)
            logger_info.info(f'{getCurrentUser(request)} 在 {str(datetime.now())[:19]} 操作《修改用户设备》权限  操作内容 {body}')
            return JsonResponse(res, status=HTTP_200_OK)

    except:
        logger_info.error(f'当前接口：{request.path} 异常，异常内容为:{traceback.format_exc()}')
        res['status'] = 400
        res['messages'] = '请求错误'
        return JsonResponse(res, status=HTTP_400_BAD_REQUEST)


@transaction.atomic
def Check(request):
    """
    设备校验
    """
    res.clear()
    try:
        if request.method == 'POST':
            body = json.loads(request.body)
            equipment_code = body.get('equipment_code')
            equipment_id = body.get('equipment_id')
            equ = Equipment.objects.get(equipment_id=equipment_id)
            equ.equipment_status = 1
            equ.save()
            res['status'] = 200
            res['message'] = '校验成功'
            createHandleLog('设备校验', str(getCurrentUser(request)), body)
            logger_info.info(f'{getCurrentUser(request)} 在 {str(datetime.now())[:19]} 操作《设备校验》权限  操作内容 {body}')
            return JsonResponse(res, status=HTTP_200_OK)

    except:
        logger_info.error(f'当前接口：{request.path} 异常，异常内容为:{traceback.format_exc()}')
        res['status'] = 400
        res['messages'] = '请求错误'
        return JsonResponse(res, status=HTTP_400_BAD_REQUEST)
